/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

const tools = require("../../js/tools");

function doLogin() {
    let accountELM = document.getElementById("account");
    let passwordELM = document.getElementById("password");
    if (accountELM === null || passwordELM === null) {
        return;
    }

    let account = accountELM.value;
    let password = passwordELM.value;
    let response = window.Action_UserInfo_Login(account, password);
    if (response === null) {
        alert("网络错误");
        return;
    }
    if (response.Status.Code !== "Suc") {
        alert(response.Status.Message);
        return;
    }

    try {
        let base64Info = tools.UnBase64(response.Token.split(".")[1]);
        window.AuthTokenInfo = JSON.parse(base64Info);
        tools.SetCookie(
            window.AuthTokenCookieName,
            response.Token,
            (window.AuthTokenInfo.lifeCycle - 300) * 1000
        );
    } catch (e) {
        alert("未知错误");
    }
}

function selectPage() {
    let willTO = "";

    if (window.AuthTokenInfo.type === API_CODE_UserRoleTypeCode_Root) {
        willTO = "root.html";
    }
    else if (window.AuthTokenInfo.type === API_CODE_UserRoleTypeCode_Maintainer) {
        willTO = "maintainer.html";
    }
    else if (window.AuthTokenInfo.type === API_CODE_UserRoleTypeCode_Manager) {
        willTO = "manager.html";
    }
    else if (window.AuthTokenInfo.type === API_CODE_UserRoleTypeCode_Leader ||
        window.AuthTokenInfo.type === API_CODE_UserRoleTypeCode_Teacher
    ) {
        willTO = "teacher.html";
    }
    else if (
        window.AuthTokenInfo.type === API_CODE_UserRoleTypeCode_Undergraduate ||
        window.AuthTokenInfo.type === API_CODE_UserRoleTypeCode_GraduateStudent ||
        window.AuthTokenInfo.type === API_CODE_UserRoleTypeCode_DoctoralStudent
    ) {
        willTO = "student.html";
    } else {
        return;
    }
    window.location.href = willTO;
}

window.onload = function () {
    tools.LoadToken();
    selectPage();

    let btn = document.getElementById("login");
    if (btn === null) {
        return
    }
    btn.onclick = function () {
        doLogin();
        selectPage();
    }
};
